package com.ftg.learn.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;

public class AudioCryptoUtil {
    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding";

    // 从密码生成16字节密钥（简单示例，生产环境建议使用更安全方式）
    public static byte[] getKeyFromPassword(String password) throws Exception {
        MessageDigest sha = MessageDigest.getInstance("SHA-256");
        byte[] key = sha.digest(password.getBytes("UTF-8"));
        return new SecretKeySpec(key, 0, 16, ALGORITHM).getEncoded();
    }

    // 加密文件
    public static void encryptFile(Path inputFile, Path outputFile, String password) throws Exception {
        byte[] keyBytes = getKeyFromPassword(password);
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, ALGORITHM);
        IvParameterSpec iv = new IvParameterSpec(new byte[16]); // 固定 IV（不安全！仅示例）

        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);

        byte[] inputBytes = Files.readAllBytes(inputFile);
        byte[] outputBytes = cipher.doFinal(inputBytes);
        Files.write(outputFile, outputBytes);
    }

    // 解密文件
    public static byte[] decryptFileToBytes(Path encryptedFile, String password) throws Exception {
        byte[] keyBytes = getKeyFromPassword(password);
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, ALGORITHM);
        IvParameterSpec iv = new IvParameterSpec(new byte[16]);

        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.DECRYPT_MODE, keySpec, iv);

        byte[] encryptedBytes = Files.readAllBytes(encryptedFile);
        return cipher.doFinal(encryptedBytes);
    }
}
